package com.ugoodtech.mdcc.client.service.impl;

import com.mysema.query.BooleanBuilder;
import com.ugoodtech.mdcc.client.controller.RequestObject.StationResponse;
import com.ugoodtech.mdcc.client.dto.JsonResponse;
import com.ugoodtech.mdcc.client.service.StationService;
import com.ugoodtech.mdcc.core.domain.*;
import com.ugoodtech.mdcc.core.helper.SearchVoId;
import com.ugoodtech.mdcc.core.repository.StationReportRepository;
import com.ugoodtech.mdcc.core.repository.StationRepository;
import com.ugoodtech.mdcc.core.repository.UserProfileRepository;
import com.ugoodtech.mdcc.core.service.SearchPermissionsService;

import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class StationServiceImpl implements StationService {

    @Autowired
    private StationRepository stationRepository;

    @Autowired
    private StationReportRepository stationReportRepository;

    @Autowired
    private UserProfileRepository userProfileRepository;

    @Autowired
    private SearchPermissionsService searchPermissionsService;

    /**
     * 查询、检查是否有此维修站
     *
     * @param province    省份
     * @param city        城市
     * @param category    类型
     * @param brand       品牌
     * @param stationName 维修站名字
     * @return
     */
    @Override
    public JsonResponse findOneStation(String province, String city, String category, String brand, String stationName, User user,Integer userType
            ,String customerStat,String customerType,String paintBrand,String productPosition,String stationNum,String userName) {
        UserProfile userProfile = userProfileRepository.findByUserId(user.getId());
        SearchVoId searchVoId;
        if (user.getUserType().equals(UserType.dealers)) {
            searchVoId = searchPermissionsService.getDealersStationId(userProfile, province, brand);
        }else {
            searchVoId = searchPermissionsService.searchColorReportByProvinceBrand(userProfile, province, brand);
        }
        List<StationNew> searchStation = new ArrayList<>();

        String[] provinces = null;
        String[] cities = null;
        String[] categories = null;
        Long[] customerStats = null;
        Long[] customerTypes = null;
        String[] paintBrands = null;
        String[] productPositions = null;

        if (StringUtils.isNotEmpty(province)){
            provinces = province.split(",");
        }
        if (!StringUtils.isEmpty(category)){
            categories = category.split(",");
        }
        if (StringUtils.isNotEmpty(city)){
            cities = city.split(",");
        }
        if (!StringUtils.isEmpty(paintBrand)){
            paintBrands = paintBrand.split(",");
        }
        if (!StringUtils.isEmpty(productPosition)){
            productPositions = productPosition.split(",");
        }
        if (!StringUtils.isEmpty(customerStat)){
            customerStats = (Long[]) ConvertUtils.convert(customerStat.split(","),Long.class);
        }
        if (!StringUtils.isEmpty(customerType)){
            customerTypes = (Long[]) ConvertUtils.convert(customerType.split(","),Long.class);
        }

        if (!searchVoId.getResultStationId().isEmpty()) {
            QStation qStation = QStation.station;
            BooleanBuilder builder = new BooleanBuilder();
            builder.and(qStation.enabled.eq(true));
            builder.and(qStation.deleted.eq(false));
            if (null != userType){
                builder.and(qStation.report_finished.eq((userType + 1)).or(qStation.report_finished.eq(3)));
            }
            builder.and(qStation.id.in(searchVoId.getResultStationId()));
            if (StringUtils.isNotEmpty(stationName)) {
                builder.and(qStation.name.like("%" + stationName + "%"));
            }
            if (provinces != null) {
                BooleanBuilder builderOr = new BooleanBuilder();
                for (String str : provinces) {
                    builderOr.or(qStation.province.like("%" + str + "%"));
                }
                builder.and(builderOr);
            }
            if (cities != null) {
                builder.and(qStation.city.in(cities));
            }
            if (categories != null) {
                builder.and(qStation.category.in(categories));
            }
            if (StringUtils.isNotEmpty(brand)) {
                builder.and(qStation.brand.like("%" + brand + "%"));
            }
            if (customerStats != null) {
                builder.and(qStation.customerStat.in(customerStats));
            }
            if (customerTypes != null) {
                builder.and(qStation.customerType.in(customerTypes));
            }
            if (paintBrands!=null) {
                BooleanBuilder builderOr = new BooleanBuilder();
                for (String str: paintBrands) {
                    builder.or(qStation.paintBrand.like("%" + str + "%"));
                }
                builder.and(builderOr);
            }
            if (StringUtils.isNotEmpty(stationNum)) {
                builder.and(qStation.stationNum.like("%" + stationNum + "%"));
            }
            if (productPositions!=null) {
                BooleanBuilder builderOr = new BooleanBuilder();
                for (String str: productPositions) {
                    builder.and(qStation.productPosition.like("%" + str + "%"));
                }
                builder.and(builderOr);
            }
            if (StringUtils.isNotEmpty(userName)){
                QUserProfile qUserProfile = QUserProfile.userProfile;
                BooleanBuilder userBuilder = new BooleanBuilder();
                userBuilder.and(qUserProfile.deleted.eq(false));
                userBuilder.and(qUserProfile.enabled.eq(true));
                userBuilder.and(qUserProfile.realName.like("%"+userName+"%"));
                List<UserProfile> list = (List<UserProfile>) userProfileRepository.findAll(userBuilder);
                if (list == null || list.size()==0){
                    return JsonResponse.successResponseWithData(new ArrayList<>());
                }
                List<Long> ids = new ArrayList<>();
                for (UserProfile up: list){
                    ids.add(up.getUser().getId());
                }
                builder.and(qStation.user.id.in(ids));
            }
            List<Station> station = (List<Station>) stationRepository.findAll(builder);
            for (Station s : station) {
                StationNew stationNew = new StationNew();
                stationNew.setName(s.getName());
                stationNew.setOtherBrand(s.isOtherBrand());
                stationNew.setStationNum(s.getStationNum());
                stationNew.setContact(s.getContact());
                stationNew.setUser(s.getUser());
                stationNew.setBrand(s.getBrand());
                stationNew.setCheckStation(s.isCheckStation());
                stationNew.setCity(s.getCity());
                stationNew.setColorReportId(s.getColorReportId());
                stationNew.setProvince(s.getProvince());
                stationNew.setAddress(s.getAddress());
                stationNew.setCustomerStat(s.getCustomerStat());
                stationNew.setCustomerType(s.getCustomerType());
                stationNew.setPaintBrand(s.getPaintBrand());
                stationNew.setProductPosition(s.getProductPosition());
                stationNew.setDistrict(s.getDistrict());
                stationNew.setIsPaint(s.getIsPaint());
                stationNew.setReport_finished(s.getReport_finished());
                stationNew.setCreationTime(s.getCreationTime());
                stationNew.setCreationTimeStr(s.getCreationTimeStr());
                stationNew.setDeleted(s.isDeleted());
                stationNew.setEnabled(s.isEnabled());
                stationNew.setId(s.getId());
                stationNew.setUpdateTime(s.getUpdateTime());
                stationNew.setUpdateTimeStr(s.getUpdateTimeStr());
                searchStation.add(stationNew);
                StationReport colorReport = stationReportRepository.selectColorReport(s.getId());
                if(colorReport != null) {
                    stationNew.setReportIdFromColor(colorReport.getId());
                }
            }
            return JsonResponse.successResponseWithData(searchStation);
        }
//        QStation qStation = QStation.station;
//        BooleanBuilder builder = new BooleanBuilder();
//        builder.and(qStation.enabled.eq(true));
//        builder.and(qStation.deleted.eq(false));
//        builder.and(qStation.checkStation.eq(false));
//        if (StringUtils.isNotEmpty(stationName)) {
//            builder.and(qStation.name.like("%" + stationName + "%"));
//        }
//        if (StringUtils.isNotEmpty(province)) {
//            builder.and(qStation.province.like("%" + province + "%"));
//        }
//        if (StringUtils.isNotEmpty(city)) {
//            builder.and(qStation.city.like("%" + city + "%"));
//        }
//        if (StringUtils.isNotEmpty(category)) {
//            builder.and(qStation.category.like("%" + category + "%"));
//        }
//        if (StringUtils.isNotEmpty(brand)) {
//            builder.and(qStation.brand.like("%" + brand + "%"));
//        }
//        List<Station> station = (List<Station>) stationRepository.findAll(builder);
//        for (Station s : station) {
//            searchStation.put(s.getId(), s);
//        }
//
//        List<StationResponse> list = new ArrayList<>();
//        for (Station key : searchStation.values()) {
//            StationResponse stationResponse = new StationResponse();
//            stationResponse.setId(key.getId());
//            stationResponse.setName(key.getName());
//            list.add(stationResponse);
//        }
        return JsonResponse.successResponseWithData(searchStation);
    }

    @Override
    public JsonResponse findStations(String stationName) {
        List<StationNew> searchStation = new ArrayList<>();
        QStation qStation = QStation.station;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qStation.enabled.eq(true));
        builder.and(qStation.deleted.eq(false));
        if (StringUtils.isNotEmpty(stationName)) {
            builder.and(qStation.name.like("%" + stationName + "%"));
        }
        List<Station> station = (List<Station>) stationRepository.findAll(builder);
        for (Station s : station) {
            StationNew stationNew = new StationNew();
            stationNew.setName(s.getName());
            stationNew.setOtherBrand(s.isOtherBrand());
            stationNew.setStationNum(s.getStationNum());
            stationNew.setContact(s.getContact());
            stationNew.setUser(s.getUser());
            stationNew.setBrand(s.getBrand());
            stationNew.setCheckStation(s.isCheckStation());
            stationNew.setCity(s.getCity());
            stationNew.setColorReportId(s.getColorReportId());
            stationNew.setProvince(s.getProvince());
            stationNew.setAddress(s.getAddress());
            stationNew.setCustomerStat(s.getCustomerStat());
            stationNew.setCustomerType(s.getCustomerType());
            stationNew.setPaintBrand(s.getPaintBrand());
            stationNew.setProductPosition(s.getProductPosition());
            stationNew.setDistrict(s.getDistrict());
            stationNew.setIsPaint(s.getIsPaint());
            stationNew.setReport_finished(s.getReport_finished());
            stationNew.setCreationTime(s.getCreationTime());
            stationNew.setCreationTimeStr(s.getCreationTimeStr());
            stationNew.setDeleted(s.isDeleted());
            stationNew.setEnabled(s.isEnabled());
            stationNew.setId(s.getId());
            stationNew.setUpdateTime(s.getUpdateTime());
            stationNew.setUpdateTimeStr(s.getUpdateTimeStr());
            searchStation.add(stationNew);
            StationReport colorReport = stationReportRepository.selectColorReport(s.getId());
            if (null != colorReport) {
                stationNew.setReportIdFromColor(colorReport.getId());
            }
        }
        return JsonResponse.successResponseWithData(searchStation);
    }


    private List<StationResponse> toObjectList(List<Station> stations) {
        List<StationResponse> list = new ArrayList<>();
        for (Station station : stations) {
            StationResponse response = new StationResponse();
            response.setId(station.getId());
            response.setName(station.getName());
            list.add(response);
        }
        return list;
    }

    private List<Station> cleanStation(List<Station> station, List<Station> stationList) {
        List<Station> stations = new ArrayList<>();
        for (Station dealers : stationList) {
            if (station.contains(dealers)) {
                stations.add(dealers);
            }
        }
        return stations;
    }


}
